package com.zzw.initializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Set;

/**
 * 自定义web容器启动初始化器
 * 注意：想要这个类生效，必须将此类全限定名配置到 META-INF/services/javax.servlet.ServletContainerInitializer 中，
 * 		 web容器启动时会加载该路径下配置的类
 * 作用：@HandlesTypes : 扫描所有实现了WebApplicationInitializer接口的实现类，并以参数形式传入onStartUp方法
 *
 * @Author: zhangzhiwei
 * @Date: 2022/1/4 0:11
 */
@HandlesTypes({WebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

	Logger log = LoggerFactory.getLogger(MySpringServletContainerInitializer.class);

	public MySpringServletContainerInitializer() {
		System.out.println("MySpringServletContainerInitializer在初始化。。。");
	}

	public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {

		// todo: 将 DispatcherServlet 注册到web容器中
		Iterator<Class<?>> iterator = set.iterator();
		// 将Class转换成对象存放在initializerList中
		while (iterator.hasNext()) {
			Class<?> initializerClass = iterator.next();
			if (!initializerClass.isInterface() && !Modifier.isAbstract(initializerClass.getModifiers()) &&
					WebApplicationInitializer.class.isAssignableFrom(initializerClass)) {
				try {
					((WebApplicationInitializer) initializerClass.newInstance()).onStartup(servletContext);
				} catch (Exception e) {
					log.error("加载web应用初始化器异常：" , e);
				}
			}
		}


	}

}
